package com.richinfo.controller;

import com.alibaba.fastjson.JSON;
import com.richinfo.annotation.LogPrint;
import com.richinfo.common.config.Global;
import com.richinfo.common.vo.SmsAppletVo;
import com.richinfo.entity.LoginToken;
import com.richinfo.entity.query.AppsTodoQuery;
import com.richinfo.log.LogInfo;
import com.richinfo.log.LogUtils;
import com.richinfo.service.LoginTokenService;
import com.richinfo.service.SysUserService;
import com.richinfo.service.TbAppsTodoService;
import com.richinfo.util.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

import static com.richinfo.util.MD5.md5;

@Controller
@RequestMapping("")
public class SysuserController {

    private static Logger logger = Logger.getLogger(SysuserController.class);

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TbAppsTodoService tbAppsTodoService;

    @Autowired
    private LoginTokenService loginTokenService;

    @RequestMapping("/smsIndex")
    public String smsIndex() {
        return "maps";
    }

    @RequestMapping("/error/403")
    public String toPage() {
        return "error/403";
    }

    @RequestMapping("/error/404")
    public String error404() {
        return "error/404";
    }

    @RequestMapping("/reply/callback")
    @ResponseBody
    public void getTodoMessageByMobile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> list = null;
        SmsAppletVo smsAppletVo = null;
        LogInfo logInfo = null;
        String action = Constant.REPLY_CALLBACK;
        LinkedHashMap<String, Object> result = new LinkedHashMap<>();
        try {

            String json = GetRequestJsonUtils.getRequestJsonString(request);
            smsAppletVo = JsonUtils.read(json, SmsAppletVo.class);
            logInfo = LogUtils.reqLogV2(false, action, "callback", "短信小程序回调函数|请求报文", json);
            logger.info(LogUtils.getMessage(logInfo));
        } catch (Exception e) {
            logger.error("短信小程序回调函数请求解析失败", e);
            e.printStackTrace();
        }
        if (StringUtils.isBlank(smsAppletVo.getSrcTerminalId()) || StringUtils.isBlank(smsAppletVo.getDestId()) || StringUtils.isBlank(smsAppletVo.getSmsContent()) || StringUtils.isBlank(smsAppletVo.getConversationId()) || StringUtils.isBlank(smsAppletVo.getSignature())) {
            result.put("reqId", "");
            result.put("status", RespCodeEnum.ERROR_1000.getCode());
            result.put("msg", RespCodeEnum.ERROR_1000.getDesc());
        } else {
            String srcTerminalId = smsAppletVo.getSrcTerminalId();
            String destId = smsAppletVo.getDestId();
            String smsContent = smsAppletVo.getSmsContent();
            String conversationId = smsAppletVo.getConversationId();
            String signature = smsAppletVo.getSignature();
            String timeStamp = smsAppletVo.getTimeStamp();
            String nonce = smsAppletVo.getNonce();
            String msg_signature = SignatureUtil.createSignature(timeStamp, nonce, Global.getConfig("secretId"));
            if (!msg_signature.equals(signature)) {
                result.put("reqId", "");
                result.put("status", RespCodeEnum.ERROR_1060.getCode());
                result.put("msg", RespCodeEnum.ERROR_1060.getDesc());
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("mobile", srcTerminalId);
                list = sysUserService.getUserByMobile(map);
                if (null != list && list.size() > 0) {
                    List mobiles = new ArrayList();
                    mobiles.add(srcTerminalId);
                    //调用发送短信接口，将待办信息发送至对应的用户
                    List reqResults = tbAppsTodoService.sendTodoToSms(list.get(0).get("login_name").toString(), mobiles, signature, timeStamp, nonce);
                    if (reqResults.size() > 0) {
                        result.put(Constant.STATUS, RespCodeEnum.SUCCESS);
                        result.put(Constant.MSG, RespCodeEnum.SUCCESS.getDesc());
                        result.put(Constant.CONTENT, reqResults);
                    } else {
                        result.put(Constant.STATUS, RespCodeEnum.ERROR);
                        result.put(Constant.MSG, RespCodeEnum.ERROR.getDesc());
                    }
                }
            }
        }
        String jsonResult = JSONObject.fromObject(result).toString();
        logInfo = LogUtils.resLog(jsonResult, logInfo);
        logger.info(LogUtils.getMessage(logInfo));
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(jsonResult);
    }


    @RequestMapping("/reqConvertShortUrl")
    @ResponseBody
    public void reqConvertShortUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LinkedHashMap<String, Object> result = new LinkedHashMap<>();
        SmsAppletVo smsAppletVo = null;
        try {
            String json = GetRequestJsonUtils.getRequestJsonString(request);
            smsAppletVo = JsonUtils.read(json, SmsAppletVo.class);
            String signature = smsAppletVo.getSignature();
            String timeStamp = smsAppletVo.getTimeStamp();
            String nonce = smsAppletVo.getNonce();
            String url = smsAppletVo.getUrl();
            List reqResults = tbAppsTodoService.converShortUrlByParams(url, signature, timeStamp, nonce);
            if (reqResults.size() > 0) {
           /*     String mobiles=Global.getConfig("mobileList");
                List<String> mobileList = Arrays.asList(mobiles.split(","));
                for (String str : mobileList){
                    Map<String, Object> result1 = SmsUtils.send(reqResults.get(0).toString(),str,"");
                    if (MapUtils.getBooleanValue(result, "flag")) {
                        logger.info("reqConvertShortUrl.error:短信发送失败" + result1.get("message"));
                    }
                }*/
                result.put(Constant.STATUS, RespCodeEnum.SUCCESS);
                result.put(Constant.MSG, RespCodeEnum.SUCCESS.getDesc());
                result.put(Constant.CONTENT, reqResults);
            } else {
                result.put(Constant.STATUS, RespCodeEnum.ERROR);
                result.put(Constant.MSG, RespCodeEnum.ERROR.getDesc());
            }
        } catch (Exception e) {
            logger.error("短信小程序回调函数请求解析失败", e);
            e.printStackTrace();
        }
        String jsonResult = JSONObject.fromObject(result).toString();
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(jsonResult);
    }

    @RequestMapping("/sendMsg")
    @ResponseBody
    public void sendMsg(HttpServletRequest request, HttpServletResponse response){
        LinkedHashMap<String, Object> result = new LinkedHashMap<>();
        SmsAppletVo smsAppletVo = null;
        try {
            String json = GetRequestJsonUtils.getRequestJsonString(request);
            smsAppletVo = JsonUtils.read(json, SmsAppletVo.class);
            String smsContent=smsAppletVo.getSmsContent();
            String mobiles=Global.getConfig("mobileList");
            List<String> mobileList = Arrays.asList(mobiles.split(","));
            for (String str : mobileList){
                Map<String, Object> result1 = SmsUtils.send(smsContent,str,"");
                if (MapUtils.getBooleanValue(result, "flag")) {
                    logger.info("reqConvertShortUrl.error:短信发送失败" + result1.get("message"));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @RequestMapping("/skipThird")
    @ApiOperation(value = "跳转到第三方应用接口", notes = "跳转到第三方应用接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gotoUrl", value = "跳转的地址", required = true, dataType = "String"),
            @ApiImplicitParam(name = "token", value = "传递回来的token", required = true, dataType = "String")
    })
    public String skipThird(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {
        LogInfo logInfo = null;
        Map result = new HashMap();
        //RedirectView redirectTarget = new RedirectView();
        //redirectTarget.setContextRelative(true);
        String redirectUrl="";
        try {
            String gotoUrl = request.getParameter("gotoUrl");
            String token = request.getParameter("token");
//String token="myToken%_%eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNqqViouTVKyUjK0tDAwMjAyNLJQjVc1NLUwszQ2MzK3sDAwUNJRSq0oULICCpobGBmZmVvUAgAAAP__.cg4EBP7bXaNo8oIYuz29nLHKyjQPpWEta0ObsNPxCp4";
            logger.info(LogUtils.getMessage("token=" + token, Thread.currentThread().getStackTrace()[1].getMethodName(), "skipThird 请求办理跳转第三方应用接口", "请求:{url:" + gotoUrl + "}"));
            if (StringUtils.isEmpty(gotoUrl) || StringUtils.isEmpty(token)) {
                logger.error("请求参数为空|参数缺失" + "gotoUrl=" + gotoUrl + "|token=" + token);
            } else {
                /*String decodeGotoUrl = URLDecoder.decode(gotoUrl, "utf-8");
                logger.info("decodeGotoUrl=" + decodeGotoUrl);*/
                String realGotoUrl = "";
                if (gotoUrl.contains(Global.getConfig("bpmSsoUrl"))) {
                    realGotoUrl = gotoUrl.replace(Global.getConfig("bpmSsoUrl"), Global.getConfig("realSsoUrl"));
                    logger.info("替换后的url=" + realGotoUrl);
                }
                String yanzhi = Global.getConfig("yanzhi");
                String md5code = md5(token + yanzhi);
                String tokenValidateUrl = Global.getConfig("tokenValidateUrl");
                JSONObject mapParam = new JSONObject();
                mapParam.put("token", token);
                mapParam.put("signature", md5code);
                String mobile = getMobileByToken(tokenValidateUrl, mapParam.toString());
// String mobile="18402003968";
                if (StringUtils.isNotBlank(mobile)) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("mobile", mobile);
                    List<Map<String, Object>> list = sysUserService.getUserByMobile(map);
                    if (null != list && list.size() > 0) {
                        if(gotoUrl.contains(Global.getConfig("myTodoUrl"))){
                            result.put(Constant.STATUS, RespCodeEnum.SUCCESS);
                            result.put(Constant.MSG, RespCodeEnum.SUCCESS.getDesc());
                            result.put("content", gotoUrl + "?userId=" + list.get(0).get("login_name").toString());
                            logger.error("跳转我的待办为url=" + gotoUrl + "?userId=" + list.get(0).get("login_name").toString());
                            redirectUrl=gotoUrl + "?userId=" + list.get(0).get("login_name").toString();
                            //redirectTarget.setUrl(gotoUrl + "?userId=" + list.get(0).get("login_name").toString());
                            //return "redirect:"+gotoUrl + "?userId=" + list.get(0).get("login_name").toString();
                            model.addAttribute("redirectUrl", URLDecoder.decode(redirectUrl,"utf-8"));
                        }else{
                            LoginToken loginToken = loginTokenService.queryToken(list.get(0).get("id").toString());
                            if(null!=loginToken){
                                result.put(Constant.STATUS, RespCodeEnum.SUCCESS);
                                result.put(Constant.MSG, RespCodeEnum.SUCCESS.getDesc());
                                if(StringUtil.isNotBlank(realGotoUrl)){
                                    result.put("content", realGotoUrl + "&loginToken=" + loginToken.getPortalToken());
                                    logger.error("跳转第三方应用地址为url=" + realGotoUrl + "&loginToken=" + loginToken.getPortalToken());
                                    redirectUrl=realGotoUrl + "&loginToken=" + loginToken.getPortalToken();
                                    //redirectTarget.setUrl(realGotoUrl + "&loginToken=" + loginToken.getPortalToken());
                                    //return "redirect:"+realGotoUrl + "&loginToken=" + loginToken.getPortalToken();
                                    model.addAttribute("redirectUrl", URLDecoder.decode(redirectUrl,"utf-8"));
                                }else{
                                    result.put("content", gotoUrl + "&loginToken=" + loginToken.getPortalToken());
                                    logger.error("跳转第三方应用地址为url=" + gotoUrl + "&loginToken=" + loginToken.getPortalToken());
                                    //redirectTarget.setUrl(gotoUrl + "&loginToken=" + loginToken.getPortalToken());
                                    //return gotoUrl + "&loginToken=" + loginToken.getPortalToken();
                                    redirectUrl=gotoUrl + "&loginToken=" + loginToken.getPortalToken();
                                    model.addAttribute("redirectUrl", URLDecoder.decode(redirectUrl,"utf-8"));
                                }
                            }else {
                                result.put(Constant.STATUS, RespCodeEnum.ERROR);
                                result.put(Constant.MSG, RespCodeEnum.ERROR.getDesc());
                                result.put(Constant.CONTENT,"********根据手机号码查询到当前用户无对应的loginToken,无法跳转到第三方系统********");
                                //redirectTarget.setUrl("error/403");
                                model.addAttribute("redirectUrl", "error/403");
                            }

                        }
                    }else{
                        result.put(Constant.STATUS, RespCodeEnum.ERROR);
                        result.put(Constant.MSG, RespCodeEnum.ERROR.getDesc());
                        model.addAttribute("redirectUrl", "error/403");
                        //redirectTarget.setUrl("error/403");
                    }
                }else{
                    result.put(Constant.STATUS, RespCodeEnum.ERROR);
                    result.put(Constant.MSG, RespCodeEnum.ERROR.getDesc());
                    result.put(Constant.CONTENT,"根据返回的token无法获取到手机号码");
                    //redirectTarget.setUrl("error/404");
                    model.addAttribute("redirectUrl", "error/404");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "maps";
    }


    @GetMapping("/myAppTodo")
    public String myAppTodo(Model model) {
        return "error/403";
    }


    public String getMobileByToken(String tokenValidateUrl, String mapParam) {
        String mobile = "";
        try {
            String reqResult = HttpUtils.post(tokenValidateUrl, mapParam);
            logger.info("请求统一认证智能取号接口返回的结果：" + reqResult);
            if (StringUtils.isBlank(reqResult)) {
                logger.info("请求统一认证智能取号接口失败,请求地址url=：" + tokenValidateUrl + "请求参数mapParam=" + mapParam);
                return null;
            }
        /*    JSONObject reqStatus=new JSONObject();
            reqStatus.put("resCode","0");
            reqStatus.put("resMsg","成功");
            JSONObject reqResult=new JSONObject();
            reqResult.put("result","0Ju7C7I2pQZh/lg9mq/DGA==");
            reqResult.put("resStatus",reqStatus);*/
            JSONObject jsonObject = JSONObject.fromObject(reqResult);
            String resultToken = "";
            String resCode = jsonObject.getJSONObject("resStatus").getString("resCode");
            if (TokenValidateExceptionCodeEnum.Success.code().equals(resCode)) {
                resultToken = jsonObject.getString("result");
                logger.info("得到的token:" + resultToken);
            } else if (TokenValidateExceptionCodeEnum.ReqError.code().equals(resCode)) {
                logger.info("验签失败或请求IP不在白名单");
                // throw new RuntimeException("非法请求<验签失败或请求IP不在白名单>");
            } else if (TokenValidateExceptionCodeEnum.TokenError.code().equals(resCode)) {
                logger.info("token解析出错");
                //throw new RuntimeException("非法token<token解析出错>");
            } else if (TokenValidateExceptionCodeEnum.TokenErrorOrNoexist.code().equals(resCode)) {
                logger.info("token不存在或token已失效");
                // throw new RuntimeException("token不存在或token已失效");
            } else {
                logger.info("系统错误");
                // throw new RuntimeException("系统错误");
            }
            if (StringUtils.isNotBlank(resultToken)) {
                mobile = AES.deCodeAES(resultToken, Global.getConfig("aesMobileKey"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mobile;
    }


}
